﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.IO;

namespace XF.Common
{
    public class CLogger
    {
        /// <summary>
        /// 是否记录日志
        /// </summary>
        public static bool YNLog = true;

        //
        //日志文件名称
        //
        private static string LogPath
        {
            get
            {
                //if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\log"))
                //{
                //    Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\log");
                //}
                return "C:\\EWSlog\\EWSStreaming_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.Year + ".log";
            }
        }

        /// <summary>
        /// 填写日志信息
        /// </summary>
        /// <param name="message">内容</param>
        private static void LogMessage(string message)
        {
            StreamWriter writer = null;

            try
            {
                FormatMessage(ref message);

                writer = File.AppendText(LogPath);
                writer.WriteLine(message);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (null != writer)
                {
                    writer.Close();
                }
            }

        }

        /// <summary>
        /// 格式化信息
        /// </summary>
        /// <param name="message"></param>
        private static void FormatMessage(ref string message)
        {
            //int CurrentProcessId = Process.GetCurrentProcess().Id;
            //int CurrentThreadId = Thread.CurrentThread.ManagedThreadId;
            string temp = message;
            string format = "yyyy-MM-dd HH:mm:ss.fff";
            message = String.Format(CultureInfo.InvariantCulture, "{0} [pid:{1}] [tid:{2}] - {3}",
                DateTime.Now.ToString(format, CultureInfo.InvariantCulture),
                0,
                0,
                temp
                );
        }

        /// <summary>
        /// 对外信息接口
        /// </summary>
        /// <param name="message"></param>
        public static void Info(string message, bool error)
        {
            if (YNLog || error)
            {
                CLogger.LogMessage(message);
            }
        }

        /// <summary>
        /// 对外信息接口
        /// </summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public static void Info(string message)
        {
            if (YNLog)
            {
                CLogger.LogMessage(message);
            }
        }
    }
}
